package pagedbdto

import (
	"gitee.com/ichub/webcli/common/base/basedto"
	"gitee.com/ichub/webcli/common/base/baseutils/stringutils"
	"gitee.com/ichub/webcli/common/base/metadata/ichubmetadata"
	"gitee.com/ichub/webcli/common/base/metadata/metadatafactroy"
	"gitee.com/ichub/webcli/common/base/pagedto"
	"gitee.com/ichub/webcli/common/ichubcontext"
	"gitee.com/ichub/webcli/common/ichublog"
	"github.com/jinzhu/gorm"
	"github.com/sirupsen/logrus"
	"strings"
)

/*
@Title    文件名称: IchubPageDbRequest.go
@Description  描述:  IchubPageDbRequest

@Author  作者: leijianming@163.com  时间(2024-02-21 22:38:21)
@Update  作者: leijianming@163.com  时间(2024-02-21 22:38:21)
*/
const DefaultTable = ichubmetadata.DefaultTable                    //"rules"
var DefaultFields = strings.Join(ichubmetadata.DefaultFields, ",") //"rule_id,rule_key"

// 通用表查询请求数据
type IchubPageDbRequest struct {
	pagedto.IchubPageRequest

	//表名
	TableName string `json:"table_name"`
	//字段列表，分隔
	FieldsName string `json:"fields_name"`
	//返回日期转为int64
	TimeToInt bool `json:"time_to_int"`

	SubTable  *SubTableDto `json:"sub_table,omitempty"`
	JoinTable *SubTableDto `json:"join_table,omitempty"`
}

func NewIchubPageDbRequest() *IchubPageDbRequest {
	var r = &IchubPageDbRequest{
		TimeToInt: false,
	}

	r.InitProxy(r)
	return r
}

func NewPageDbRequest(pageSize int) *IchubPageDbRequest {
	var r = NewIchubPageDbRequest()
	r.PageSize = pageSize
	r.IchubPageRequest.PageSize = pageSize
	return r
}

func (this *IchubPageDbRequest) ValueOfPageRequest(that *IchubPageDbRequest) *IchubPageDbRequest {

	this.IchubPageRequest = that.IchubPageRequest
	this.IchubPageRequest.InitProxy(this.IchubPageRequest)
	this.TableName = that.TableName
	this.FieldsName = that.FieldsName
	this.TimeToInt = that.TimeToInt
	return this

}
func (this *IchubPageDbRequest) Clear() *IchubPageDbRequest {
	this.IchubPageRequest.Clear()
	this.FieldsName = ""
	this.TableName = ""
	this.TimeToInt = true
	this.SubTable = nil

	this.JoinTable = nil

	return this

}
func (this *IchubPageDbRequest) NewSubTable() *IchubPageDbRequest {
	this.SubTable = NewSubTableDto()
	return this
}
func (this *IchubPageDbRequest) FindTable() *gorm.DB {

	dbc := this.GetDB().Table(this.TableName)
	dbc = dbc.Select(this.FieldsName)

	dbc = this.BuildWhere(dbc)
	dbc = this.Order(dbc)
	dbc = this.SetLimit(dbc)

	return dbc
}
func (this *IchubPageDbRequest) DefaultTableFields() *IchubPageDbRequest {
	if len(this.TableName) == 0 {
		this.TableName = DefaultTable
		this.FieldsName = DefaultFields

	}
	return this
}
func (this *IchubPageDbRequest) FieldNames2SnakeCase() {
	var fields = strings.Split(this.FieldsName, ",")
	var f []string = []string{}
	for _, v := range fields {
		v = stringutils.Camel2Case(v)
		f = append(f, strings.TrimSpace(v))

	}
	this.FieldsName = strings.Join(f, ",")

}
func (this *IchubPageDbRequest) InitPage() {
	//ServiceTemplateCombos
	this.TableName = stringutils.Camel2Case(this.TableName)
	this.IchubPageRequest.InitPage()
}
func (this *IchubPageDbRequest) GeneralQueryDto() *pagedto.IchubPageResult {
	this.TimeToInt = true
	return this.GeneralQuery()
}
func (this *IchubPageDbRequest) MetadataQuery() *basedto.IchubResult {
	this.DefaultTableFields()
	var metadataFactroy = metadatafactroy.NewMetadataFactroy()
	var metadata = metadataFactroy.FindMetadata(this.TableName)
	if !metadata.TableExist {
		return basedto.NewIchubResult().FailMessage("表不存在！")
	}
	return basedto.NewIchubResult().SuccessData(metadata)

}

func (this *IchubPageDbRequest) GeneralQuery() *pagedto.IchubPageResult {

	this.DefaultTableFields()

	this.InitPage()
	var metadataFactroy = metadatafactroy.NewMetadataFactroy()
	var meta = metadataFactroy.FindFields(this.TableName, this.FieldsName)
	if !meta.TableExist {
		return pagedto.NewPageResultError("表不存在！")
	}
	this.FieldsName = meta.FieldsName
	this.FieldNames2SnakeCase()
	logrus.Info("IchubPageDbRequest GeneralQuery req =", this.ToPrettyString())

	fileName := this.TableName + "_pagerequest.json"
	ichubcontext.CommonContext.WriteDaoFile(fileName, this.IchubPageRequest.ToPrettyString())

	count, err := this.CountTable(this.TableName)
	if err != nil {

		logrus.Error(err)
		return pagedto.NewPageResultError(err.Error())
	}
	var pageResult = pagedto.ValueOf(&this.IchubPageRequest)
	pageResult.Total = count
	if count == 0 {
		return pageResult
	}
	var db = this.FindTable()
	rows, errs := db.Rows()
	if errs != nil {
		logrus.Error(errs)
		return pagedto.NewPageResultError(errs.Error())

	}
	defer func() {
		if err := rows.Close(); err != nil {
			logrus.Error(err)
		}
	}()
	var ichubRecords = ichubmetadata.NewIchubRecords()

	err = ichubRecords.TableFields(this.TableName, this.FieldsName).ScanRows(this.TimeToInt, rows)
	if err != nil {
		logrus.Error(err)
		return pagedto.NewPageResultError(err.Error())
	}

	pageResult.Data = ichubRecords.Records

	if this.IfSubTable() {
		this.QuerySubTable(ichubRecords.Records)
	}
	fileName = this.TableName + "_pageresult.json"
	ichubcontext.CommonContext.WriteDaoFile(fileName, pageResult.ToPrettyString())

	ichublog.Log(pageResult)
	return pageResult

}

func (this *IchubPageDbRequest) IfSubTable() bool {
	return this.SubTable != nil
}
func (this *IchubPageDbRequest) QuerySubTable(records []map[string]interface{}) {
	var req = NewIchubPageDbRequest()
	req.TableName = this.SubTable.TableName
	req.PageSize = this.SubTable.PageSize
	req.FieldsName = this.SubTable.FieldsName
	req.TimeToInt = this.TimeToInt
	var key, subkey string
	for k, v := range this.SubTable.JoinKeys {
		key = k
		subkey = v
	}
	for _, v := range records {
		req.Eq(subkey, v[key])
		var data = req.GeneralQuery()
		v[this.SubTable.TableName] = data.Data
	}

}
